<?php
/**
 *
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2019/5/28 14:36
 * @copyright PanxSoft Inc.
 */

namespace App\Http\Controllers\App\V1;


use App\Exceptions\ApiAbstractException;
use App\Http\Controllers\ApiController;
use App\Services\Utils\Guard;
use Illuminate\Http\Request;

class UserDeviceController extends ApiController
{
    const ROUTES = [
        'update'  => 'app.v1.userDevice.update',
        'index'   => 'app.v1.userDevice.index',
        'store'   => 'app.v1.userDevice.store',
        'destroy' => 'app.v1.userDevice.destroy',
    ];

    /**
     * 设备列表
     *
     * @return array|\Illuminate\Http\Response
     */
    public function index()
    {
        $user_devices = Guard::user()
            ->userDevices()
            ->with('device.localeDescription')
            ->oldest('sort_order')
            ->latest('created_at')
            ->get();

        return $this->response(compact('user_devices'));
    }

    /**
     * 新增用户设备
     *
     * @param Request $request
     *
     * @return array|\Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $store_data = $request->only([
            'device_id', 'mac', 'name'
        ]);

        $user_device = Guard::user()
            ->userDevices()
            ->with('device.localeDescription')
            ->create($store_data);

        return $this->response(compact('user_device'));
    }

    /**
     * 更新用户设备信息
     *
     * @param Request $request
     *
     * @param $device_id
     *
     * @return array|\Illuminate\Http\Response
     * @throws ApiAbstractException
     */
    public function update(Request $request, $device_id)
    {
        /** @var $user_device $user_device */
        $user_device = Guard::user()
            ->userDevices()
            ->whereKey($device_id)
            ->first();
            $this->checkItemExist($user_device, trans('checker.app.user_device'));

        $update_data = array_filter($request->only([
            'name'
        ]));

        $updated = $user_device->update($update_data);

        return $this->response(compact('user_device', 'updated'));
    }

    /**
     * @param $device_id
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function destroy($device_id)
    {
        /** @var $user_device $user_device */
        $user_device = Guard::user()
            ->userDevices()
            ->whereKey($device_id)
            ->first();
        $this->checkItemExist($user_device, trans('checker.app.user_device'));

        $deleted = $user_device->delete();

        return $this->response(compact('user_device', 'deleted'));
    }
}